package cn.codingjc.provider.action;

import cn.codingjc.common.dto.DeptDTO;
import cn.codingjc.service.IDeptService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author shenjicheng
 * @date 2022/7/2 6:59 PM
 */

@Slf4j
@RestController
@RequestMapping("/provider/dept/*")
public class DeptAction {

    @Autowired
    private IDeptService deptService;

    @GetMapping("get/{id}")
    @ApiOperation(value = "部门查询", notes = "根据部门编号查询部门详细信息")
    public Object get(@PathVariable("id") long id) {
        printRequestheaders("get");
        return deptService.get(id);
    }

    @PostMapping("add")
    @ApiOperation(value = "部门添加", notes = "增加新的部门信息")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "dto", required = true, dataType = "DeptDTO", value = "部门的传输对象实例")}
    )
    public Object add(@RequestBody DeptDTO dto) {
        printRequestheaders("add");
        return this.deptService.add(dto);
    }

    @GetMapping("list")
    @ApiOperation(value = "部门查询", notes = "查询部门列表完整信息")
    public Object list() {
        printRequestheaders("list");
        return this.deptService.list();
    }

    @GetMapping("split")
    @ApiOperation(value = "部门分页查询", notes = "分页查询部门列表信息")
    @ApiImplicitParams({
                    @ApiImplicitParam(name = "cp", value = "当前所在页", required = true, dataType = "int"),
                    @ApiImplicitParam(name = "ls", value = "页数大小", required = true, dataType = "int"),
                    @ApiImplicitParam(name = "col", value = "模糊查询字段", required = true, dataType = "string"),
                    @ApiImplicitParam(name = "kw", value = "模糊查询关键字", required = false, dataType = "sring")
        }
    )
    public Object split(int cp, int ls, String col, String kw) {
        printRequestheaders("split");
        return this.deptService.split(cp, ls, col, kw);
    }

    /**
     * 实现所有请求头信息的输出
     */
    private void printRequestheaders(String requestName) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("【{}】头信息：{} = {}", requestName, headerName, request.getHeader(headerName));
        }

    }
}
